package org.niugang.coding.oauth;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.niugang.coding.utils.RsaUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 加载配置信息
 *
 * @author Created by niugang on 2019/01/11/13:40
 */
@Slf4j
@Data
@Component(value = "jwtProperties")
@ConfigurationProperties(prefix = "spring.jwt")
public class JwtProperties {

    private String secret;

    private String pubKeyPath;

    private String priKeyPath;

    private Integer expire;

    private PrivateKey privateKey;

    private PublicKey publicKey;


    @PostConstruct
    public void init() {
        try {
            //首先判断公钥私钥是否存在，不存在则先生成公钥私钥
            createDir(pubKeyPath);
            createDir(priKeyPath);
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);

            if (!pubKey.exists() || !priKey.exists()) {
                //创建公钥，私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            //公钥私钥都存在
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥私钥失败", e);
            throw new RuntimeException();
        }
    }

    /**
     * 创建文件夹h
     */
    private void createDir(String path) {
        int i = path.lastIndexOf("/");
        String pubKeyDirPath = path.substring(0, i);
        File pubKeyDirFile = new File(pubKeyDirPath);
        if (!pubKeyDirFile.exists()) {
            pubKeyDirFile.mkdirs();
        }
    }
}
